package com.van.controller;

import com.van.Service.SysLogService;
import com.van.Service.UpFileService;
import com.van.entity.ResPonObject;
import com.van.entity.SysLog;
import com.van.entity.UpFile;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author VanKa qq:2395073039
 * @date 2021/6/22 16:43
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UpFileService upFileService;
    @Autowired
    private SysLogService sysLogService;

    static SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
    static SimpleDateFormat formatter3 = new SimpleDateFormat("HHmmss");

    /**
     * 上传图片
     * @param request e
     * @param file e
     * @param type 1 文章图片
     * @return e
     * @throws IOException e
     */
    @ResponseBody
    @RequestMapping("/img")
    public ResPonObject upImg(
            HttpServletRequest request,
            @RequestParam("file") MultipartFile file,
            @RequestParam(name = "type", required = false, defaultValue = "-1") int type
    ) throws IOException {
        System.out.println("type:" + type);
        //判断文件大小
        if (file.getSize() > 1024 * 1024 * 2) {
            return new ResPonObject("你的上传的图片太大了", ResPonObject.Status.ERROR);
        }
        //判断文件是否为图片 image/jpeg
        String contentType = file.getContentType();
        if (!contentType.contains("image")) {
            return new ResPonObject("请确上传的是图片", ResPonObject.Status.ERROR);
        }
        if (type < 0) {
            return new ResPonObject("参数丢失", ResPonObject.Status.ERROR);
        }
        //todo 获取用户身份

        if (file.isEmpty()) {
            return new ResPonObject("上传失败，请选择文件", ResPonObject.Status.ERROR);
        }
        //保存文件
        String s = saveFile(file, type, 0);
        if (Strings.isEmpty(s)) {
            return new ResPonObject("文件保存失败", ResPonObject.Status.ERROR);
        }
        //todo 保存到数据库中
        UpFile up = new UpFile(type, s, "xxx上传图片");
        boolean on = upFileService.save(up);
        sysLogService.save(new SysLog(SysLog.Status.Up_Img, "上传图片", up, 2));
        return new ResPonObject(on, up,"上传失败");
    }

    /**
     * 判断文件夹是否存在，不存在则创建
     *
     * @param name 文件夹
     */
    private static void ifThere(String name) {
        File folder = new File(name);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.mkdirs();
        }
    }

    /**
     * 判断文件是否存在 不存在就保存
     *
     * @param path 路径
     * @return
     */
    private static boolean checkLocalFile(String path, MultipartFile file) throws IOException {
        boolean on = true;
        File f = new File(path);
        if (!f.exists()) {
            file.transferTo(f);
            on = false;
        }
        return on;
    }

    /**
     * 保存文件
     *
     * @param file 文件
     * @param type 1 图片
     * @param id
     * @return
     */
    public static String saveFile(MultipartFile file, int type, int id) {

        File directory = new File("");
        directory.setWritable(true, false);
        String fileName = file.getOriginalFilename();//获取当前文件名称
        String paperFile = "";//设置文件保存地址全路径
        String imgTime = formatter2.format(new Date());//自定义保存目录
        String filePath = ""; //设置文件保存地址
        String projectFile;//获取当前项目的路径

        try {
            boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");// 判断系统环境

            projectFile = directory.getCanonicalPath();// 获取项目地址

            filePath = projectFile + "/img/" + imgTime + "/" + id + "_";

            ifThere(filePath);//判断文件夹是否存在，不存在则创建

            boolean on;
            do {
                String imgName = formatter3.format(new Date()) + new Double(Math.random() * 100).intValue();//自定义文件前缀
                paperFile = filePath + imgName + fileName;
                on = checkLocalFile(paperFile, file);//判断文件是否存在
            } while (on);

            return paperFile;

        } catch (IOException ignored) {

        }
        return null;
    }
}
